module repository.HistoryRepository;

import hunt.entity;
import hunt.logging;
import std.conv : to;
import bootstrap.DatabaseBootstrap;
import model;
import message.MsgDefine;
import std.format;
import std.base64;

import hunt.framework;

class HistoryRepository : EntityRepository!( HistoryMsg , int) {

  this()
  {
    super(defaultEntityManager());
  }


  HistoryMsg[] findAllByID(string userId)
  {
    return findAll(new Condition("%s = %s" , Field.toId , userId));
  }

  void putHistoryMsg(Msg obj)
  {
    scope(exit)
    {
      _manager.close();
    }

    // if (obj.type == MsgType.NOTICE_BACKOFF)
    // {
    //   auto suc = backoffHistory(obj.messageId);
    //   if (!suc)
    //   {
    //     return ;
    //   }
    // }


    auto m = new HistoryMsg;
    m.chatId = obj.chatId;
    m.fromId = obj.fromUserId;
    m.toId = obj.localId;
    m.message = obj.message;
    m.duration = obj.duration;
    m.createTime = obj.msgTime;
    m.type = cast(uint)obj.type;
    m.ossObjectName = obj.ossObjectName;
    m.fileSize = obj.fileSize;
    m.messageId = obj.messageId;
    m.binaryData = cast(string) Base64.encode ( cast(ubyte[]) obj.binaryBase64 );
    m.backoff = 0;
    insert(m);

    // // auto insert = _manager.createQuery!(HistoryMsg)("INSERT INTO HistoryMsg u(u.chatId,u.fromId,u.toId,u.message,u.duration,u.createTime,u.type,u.ossObjectName,u.fileSize,u.messageId,u.binaryData) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
    // // insert.setParameter(1,obj.chatId);
    // // insert.setParameter(2,obj.fromUserId);
    // // insert.setParameter(3,obj.localId);
    // // insert.setParameter(4,obj.message);
    // // insert.setParameter(5,obj.duration);
    // // insert.setParameter(6,obj.msgTime);
    // // insert.setParameter(7,cast(uint)obj.type);
    // // insert.setParameter(8,obj.ossObjectName);
    // // insert.setParameter(9,obj.fileSize);
    // // insert.setParameter(10,obj.messageId);
    // // insert.setParameter(11,obj.binaryBase64);
    // // insert.exec();
  }

  void getSessionList(string id,SessionListRes res)
  {
    scope(exit)
    {
      _manager.close();
    }
    string sql = "SELECT chat_id, max(create_time) as mm  FROM logic_im_history_msg WHERE to_id = '" ~ id ~ "' GROUP BY chat_id";
    auto  query = _manager.getSession.query(sql);
    foreach(v;query)
    {
        Sessions session = new Sessions;
        string chatId = v.getValue("chat_id").toString();
        long createTime = v.getValue("mm").toString().to!long;
        session.chatId = chatId;
        session.timestamp = createTime;
        res.sessions ~= session;
    }
  }

  HistoryMsg[] getHistoryLimit(HistoryMsgREQ req)
  {
      scope(exit)
      { 
        _manager.close();
      }
      if(req.messageId.length != 0)
      {
          //SELECT * FROM "logic_im_history_msg" WHERE id < (select id from "logic_im_history_msg" WHERE message_id = '%s' limit 1) ;

          string sql = "select * from HistoryMsg a where a.toId = '%s' AND a.chatId = '%s' AND a.id < 
          (select id from logic_im_history_msg WHERE message_id = '%s' limit 1)
           ORDER BY a.id DESC LIMIT %s";

          sql = format(sql, req.clientId, req.chatId, req.messageId, req.limit);

          auto  query = _manager.createQuery!(HistoryMsg)(sql);
          //setParameter("toId", req.clientId).
          //setParameter("groupId", req.chatId).
          //setParameter("ID",to!uint(req.messageId)).
          //setParameter("LM",req.limit);
          return query.getResultList();
      }else
      {
        string sql = "select * from HistoryMsg a where a.toId = '%s' AND a.chatId = '%s' ORDER BY a.id DESC LIMIT %s";

        sql = format(sql, req.clientId, req.chatId, req.limit);

        auto  query = _manager.createQuery!(HistoryMsg)(sql);
        //setParameter("toId", req.clientId).
        //setParameter("groupId", req.chatId).
        //setParameter("LM",req.limit);
        return query.getResultList();
      }

  }

  bool backoffHistory(string msgId)
  {
    scope(exit)
    {
      _manager.close();
    }
    
    auto upd = _manager.createQuery!(Offline)("UPDATE HistoryMsg SET backoff = :backoff where message_id = :message_id");
    upd.setParameter("message_id",msgId);
    upd.setParameter("backoff",1);

    try{
      upd.exec();
    }
    catch(Exception e)
    {
      logError("backoffHistory error : %s",e.msg);
    }

    return true;
  }
}


